<template>
  <div>
    <my-breadcrumb :items="['轮播图管理', '轮播图设置']"/>
    <div class="goods_banner">
      <h2>商品轮播图</h2>
      <Row :gutter="16">
        <i-col span="6" v-for="(banner, index) in goodsBanner" :key="index">
          <Card>
            <h3>{{ banner.title }}</h3>
            <div class="banner">
              <img :src="staticUrl + banner.path" alt="轮播图" width="100%">
            </div>
            <div class="goods_info">
              <div class="goods_img">
                <img :src="staticUrl + banner.goodsInfo.mainImagePath" alt="商品图片" width="100%">
              </div>
              <div class="info">
                <p>商品：{{ banner.goodsInfo.title }}</p>
                <p>权重：{{ banner.sortWeight }}</p>
                <!--<Button size="small" type="primary" @click="toUpdateGoods(id)">更换商品</Button>-->
              </div>
            </div>
            <div class="btn">
              <!--<Upload action="#" :before-upload="handleBeforeUpload">
                <Button size="small" type="ghost" @click="toUpdateBanner(banner)">轮播图更换</Button>
              </Upload>-->
              <Button size="small" type="text" @click="delBanner(banner)">删除</Button>
            </div>
          </Card>
        </i-col>
        <i-col span="6">
          <div class="add" v-if="!addMax">
            <Upload
              :show-upload-list="false"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              :before-upload="handleBeforeUpload"
              action="#">
              <div style="height:100%;" @click="uploadGoods">
                <Icon type="camera" size="20"></Icon>点击上传商品轮播图
              </div>
            </Upload>
          </div>
          <div v-else class="max">仅限五张轮播图，可先删除再次添加</div>
        </i-col>
      </Row>
    </div>
    <div class="text_banner">
      <h2>文本轮播图</h2>
      <Row :gutter="16">
        <i-col span="6" v-for="(banner, index) in textBanner" :key="index">
          <Card>
            <div class="banner">
              <img :src="staticUrl + banner.path" alt="轮播图" width="100%">
            </div>
            <div class="title">
              <p>标题：{{ banner.title }}</p>
              <p>权重：{{ banner.sortWeight }}</p>
            </div>
            <div class="btn">
              <!--<Upload action="#" :before-upload="handleBeforeUpload">
                <Button size="small" type="ghost" @click="toUpdateBanner(banner)">轮播图更换</Button>
              </Upload>-->
              <Button type="text" size="small" @click="likePhone(banner.textList)">预览</Button>
              <!--<Button type="text" size="small" @click="updateRich(banner.textList)">修改</Button>-->
              <Button type="text" size="small" @click="delBanner(banner)">删除</Button>
            </div>
          </Card>
        </i-col>
        <i-col span="6">
          <div class="add_text" v-if="!addMax">
            <Upload
              :show-upload-list="false"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              :before-upload="handleBeforeUpload"
              action="#">
              <div style="height:100%;" @click="uploadText">
                <Icon type="camera" size="20"></Icon>点击上传文本轮播图
              </div>
            </Upload>
          </div>
          <div v-else class="max">仅限五张轮播图，可先删除再次添加</div>
        </i-col>
      </Row>
    </div>
    <div class="rich_text" v-show="showRichText" id="richText">
      <rich-text ref="richText"></rich-text>
      <div style="text-align: right;margin-top: 8px;">
        <Button type="primary" @click="tempView">预览</Button>
        <Button type="primary" @click="addTextBanner">提交</Button>
        <Button type="text" @click="cancelRich">取消</Button>
      </div>
    </div>
    <image-util ref="imageUtil" @cropImg="cropImg" :fixed-number="[375, 157]"></image-util>
    <Modal v-model="showGoods" :styles="{top: '10px'}" title="选择轮播图对应的商品">
      检索商品：<Input v-model="title" placeholder="根据商品名称检索" @on-enter="searchGoods" style="width: 200px;"/>
      <Button type="primary" @click="searchGoods">检索</Button>
      <div style="overflow: hidden;margin-top: 16px;" v-show="goods[0]">
        <h3>点击商品即确认选择</h3>
        <ul>
          <li v-for="(item, index) in goods" :key="index" class="select" @click="selectGoods(item)">
            <img :src="staticUrl + item.mainImagePath" alt="图片" width="40" style="float: left;">
            <p style="line-height: 40px;float: left;">{{ item.title }}</p>
          </li>
        </ul>
      </div>
    </Modal>
    <Modal v-model="showPhone" width="420" :styles="{top: '10px'}" title="手机预览简图">
      <div class="phone" v-html="phoneHtml"></div>
    </Modal>
  </div>
</template>

<script>
import imageUtil from '../../common/imageUtil'
import richText from './richText'
export default {
  name: 'banner',
  data () {
    return {
      url: {
        list: '/sowing/map/get/back/stage',
        add: '/sowing/map/add/goods', // smInfoDto[] sowingMapImages
        addText: '/sowing/map/add/text',
        remove: '/sowing/map/remove',
        update: '/sowing/map/modify/basic',
        sowing: '/sowing/map/modify/image',
        search: '/goods/manage/get/goods/by/condition'
      },

      goodsBanner: [],
      textBanner: [],

      imgBlob: null,
      showGoods: false,
      title: '',
      goods: [],

      goodsParams: {
        title: '',
        goodsId: null,
        type: 0,
        sortWeight: 0
      },

      isAddBanner: true,
      isUploadText: true,
      isUpdateText: false,
      showRichText: false,

      showPhone: false,
      phoneHtml: '',

      addMax: false
    }
  },
  methods: {
    uploadText () {
      this.isUploadText = true
      this.isUpdateText = false
      this.goodsParams.type = 2
    },
    uploadGoods () {
      this.goodsParams.type = 1
      this.isUploadText = false
    },

    handleBeforeUpload (e) {
      this.$Modal.confirm({
        title: '输入轮播图标题',
        render: h => {
          return h('div', [
            h('Input', {
              props: {
                placeholder: '请输入轮播图标题',
                value: this.goodsParams.title
              },
              style: {
                marginBottom: '8px'
              },
              on: {
                input: (e) => {
                  this.goodsParams.title = e
                }
              }
            }),
            h('span', '轮播图权重'),
            h('InputNumber', {
              props: {
                min: 0,
                max: 10,
                value: this.goodsParams.sortWeight
              },
              on: {
                input: (e) => {
                  this.goodsParams.sortWeight = e
                }
              }
            }),
            h('span', '根据权重对轮播图进行排序')
          ])
        },
        onOk: () => {
          if (this.goodsParams.title !== '') {
            this.isAddBanner = true
            this.$refs.imageUtil.setImage({e, name: 'banner'})
          }
        }
      })
      return false
    },
    cropImg (data) {
      this.imgBlob = data.blob
      if (this.isUploadText) {
        // 上传文本
        this.$Message.info('请在页面下方编辑页面后提交')
        this.showRichText = true
        this.$nextTick(() => {
          let con = document.getElementById('content')
          con.scrollTop = con.scrollHeight
        })
      } else {
        this.showGoods = true
      }
    },

    searchGoods () {
      if (this.title === '') {
        return
      }
      let params = {
        provideGoodsQueryConditionDto: {title: this.title},
        goodsPageQuery: {
          pageNum: 1,
          pageSize: 30
        }
      }
      this.$ajax.post(this.url.search, JSON.stringify(params)).then(res => {
        if (res.data.success) {
          this.goods = res.data.data.pageInfo.list
        }
      })
    },
    selectGoods (goods) {
      if (this.isAddBanner) {
        this.addBanner(goods)
      } else {
        this.updateGoods(goods)
      }
    },
    addBanner (goods) {
      this.goodsParams.goodsId = goods.goodsId
      let formData = new FormData()
      formData.append('smInfoDto', JSON.stringify(this.goodsParams))
      formData.append('sowingMapGoodsImages', this.imgBlob, 'file.jpg')
      this.$ajax.post(this.url.add, formData, {headers: {'Content-Type': 'multipart/form-data'}})
        .then(res => {
          if (res.data.success) {
            this.showGoods = false
            this.$Message.success('添加成功')
            this.initBanner()
          }
        })
    },

    addTextBanner () {
      this.goodsParams.text = this.$refs.richText.getRichData()
      if (this.isUpdateText) {
        // 更新
      } else {
        delete this.goodsParams.goodsId
        let formData = new FormData()
        console.log(this.goodsParams)
        formData.append('smInfoDto', JSON.stringify(this.goodsParams))
        formData.append('sowingMapTextImages', this.imgBlob, 'file.jpg')
        this.$ajax.post(this.url.addText, formData, {headers: {'Content-Type': 'multipart/form-data'}})
          .then(res => {
            if (res.data.success) {
              this.showRichText = false
              this.$Message.success('添加成功')
              this.initBanner()
            }
          })
      }
    },

    updateGoods (row) {
      // 更换轮播图
    },
    toUpdateGoods (id) {
      this.goodsParams.goodsId = id
      this.isAddBanner = false
      this.goods = []
    },

    toUpdateBanner (banner) {
      this.goodsParams.goodsId = banner.id
      this.goodsParams.title = banner.title
    },

    delBanner (banner) {
      // 删除
      let params = {
        sowingMapId: banner.id,
        type: banner.type,
        path: banner.path
      }
      this.$Modal.confirm({
        title: '删除轮播图',
        content: '你确定删除该轮播图吗？',
        onOk: () => {
          this.$ajax.post(this.url.remove, params)
            .then(res => {
              if (res.data.success) {
                this.$Message.success('删除成功')
                this.initBanner()
              }
            })
        }
      })
    },

    cancelRich () {
      this.$refs.richText.initData('')
      this.showRichText = false
    },
    updateRich (html) {
      this.$refs.richText.initData(html)
      this.showRichText = true
      this.isUpdateText = true
      this.$Message.info('请到下方编辑修改，之后提交')
    },
    likePhone (html) {
      this.showPhone = true
      this.phoneHtml = html
    },
    tempView () {
      this.likePhone(this.$refs.richText.getRichData())
    },

    initBanner () {
      this.$ajax.get(this.url.list)
        .then(res => {
          if (res.data.success) {
            this.textBanner = res.data.data.sowingMapTextVoList
            let temp = []
            res.data.data.sowingMapGoods.goodsInfoList && res.data.data.sowingMapGoods.goodsInfoList.forEach(item => {
              temp['G' + item.goodsId] = item
            })
            res.data.data.sowingMapGoods.sowingMap && res.data.data.sowingMapGoods.sowingMap.forEach(item => {
              item.goodsInfo = temp['G' + item.goodsId]
            })
            this.goodsBanner = res.data.data.sowingMapGoods.sowingMap
            if (this.textBanner.length + this.goodsBanner.length >= 5) {
              this.addMax = true
            } else {
              this.addMax = false
            }
          }
        })
    }
  },
  components: {
    imageUtil,
    richText
  },
  created () {
    this.initBanner()
  }
}
</script>

<style scoped>
  .goods_banner{
    border-bottom: 1px solid #dddee1;
    padding-bottom: 16px;
  }
  .goods_info{
    position: relative;
    height: 70px;
    width: 100%;
    margin-top: 8px;
    border-bottom: 1px solid #dddee1;
  }
  .goods_img{
    position: absolute;
    top: 0;
    left: 0;
    width: 70px;
    height: 70px;
    height: 110px;
  }
  .info{
    position: absolute;
    left: 78px;
    right: 0;
    top: 0;
    font-size: 12px;
  }
  .info p{
    line-height: 26px;
  }
  .banner{
    width: 100%;
  }
  .btn{
    width: 100%;
    text-align: right;
    margin-top: 10px;
  }
  .add{
    height: 240px;
    line-height: 240px;
  }
  .add, .add_text{
    text-align: center;
    font-size: 20px;
    border: 2px dotted #dddee1;
    border-radius: 5px;
    cursor: pointer;
  }
  .add:hover, .add_text:hover{
    border: 2px dotted #409eff;
  }
  .text_banner{
    margin-top: 16px;
  }
  .title{
    margin-top: 10px;
  }
  .add_text{
    height: 200px;
    line-height: 200px;
  }
  .rich_text{
    margin-top: 10px;
  }
  .phone{
    width: 375px;
    height: 600px;
    margin: 0 auto;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid #dddee1;
    border-radius: 16px;
  }
  .max{
    font-size: 16px;
    line-height: 40px;
  }
  .select{
    cursor: pointer;
    float: left;
    overflow: hidden;
    padding: 8px;
  }
  .select:hover{
    background-color: #dddee1;
  }
</style>
